#!/usr/bin/env node

// PWM命令调试工具
const { spawn } = require("child_process");
const { resolve } = require("path");

console.log("启动PWM调试工具...");

// 创建GPIO进程连接
let gpioProcess;

try {
  gpioProcess = spawn(`sudo`, [
    process.execPath,
    resolve(__dirname, "./lib/gpio.js"),
  ]);

  console.log("GPIO进程已启动");

  // 监听GPIO进程的输出
  gpioProcess.stdout.on("data", (data) => {
    console.log(`[GPIO输出] ${data.toString()}`);
  });

  gpioProcess.stderr.on("data", (data) => {
    console.log(`[GPIO错误] ${data.toString()}`);
  });

  gpioProcess.on("error", (error) => {
    console.error(`[GPIO进程错误] ${error.message}`);
  });

  // 等待进程启动
  setTimeout(() => {
    console.log("开始发送PWM命令...");
    
    // 发送PWM命令
    const commands = [
      "pwm 13 0.5",
      "pwm 13 0.8", 
      "pwm 13 0",
      "pwm 13 -0.3",
      "pwm 13 0"
    ];

    commands.forEach((cmd, index) => {
      setTimeout(() => {
        console.log(`发送命令: ${cmd}`);
        gpioProcess.stdin.write(`${cmd}\n`);
      }, index * 2000);
    });

    // 5秒后退出
    setTimeout(() => {
      console.log("测试完成，退出进程");
      gpioProcess.stdin.write(`exit\n`);
      process.exit(0);
    }, 12000);

  }, 1000);

} catch (error) {
  console.error(`启动失败: ${error.message}`);
  process.exit(1);
}